package com.bgi.uims.pub.web;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.bgi.uims.common.service.ICommonService;
import com.bgi.uims.module.sys.operatorlog.dto.SysOperatorLog;
import com.bgi.uims.module.sys.user.dto.User;
import com.bgi.uims.pub.utils.Constant;
import com.bgi.uims.pub.utils.DateUtil;
import com.bgi.uims.pub.utils.PublicMethod;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 
 * ClassName:ActionVisitTimeInterceptor 
 * Function: 拦截器栈用于计算访问入口到出口的使用时间
 * Reason:	 TODO 
 * @CreateDate:2015年4月2日 下午12:52:17
 * @author   WEN
 * @version  
 * @since    JDK 1.7
 * @see
 */
@Controller
@Scope("prototype")
public class ActionVisitTimeInterceptor extends AbstractInterceptor{

	private static final long serialVersionUID = 1L;
	@Resource
	private ICommonService commonService;

	@SuppressWarnings("static-access")
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpSession session=request.getSession();
		String actionname=invocation.getInvocationContext().getContext().getName();
		Map<String, Object> contextMap = invocation.getInvocationContext().getContextMap();
		SysOperatorLog log = new SysOperatorLog();
		String start=DateUtil.getSysDate();
		String result=invocation.invoke();
		String end=DateUtil.getSysDate();
		User user=(User) session.getAttribute(Constant.LOGINUSER);
		if(user!=null)
		{
			//未登录用户暂时不存日志
			//执行Insert
			log.setInsertSql(Constant.SQL_LOG_OPERATOR_INSERT);
			//Java生成32位的GUID作为主键
//			log.setOperatorId((new RandomGUID()).toString());
			log.setWorkNumber(user.getWorkNumber());
			log.setUserName(user.getUserName());
			log.setRealName(user.getRealName());
			log.setOperatorIp(PublicMethod.getIpAddr(request));
			log.setOperatorType("4");
			log.setUserId(user.getUserId());
			String url=request.getRequestURI();
//			log.setFullUrl(request.getRequestURI());
//			log.setOperatorUrl(actionname);//url.substring(url.lastIndexOf("/")+1, url.length())
//			log.setStartTime(start);//开始时间
//			log.setEndTime(end);//结束时间
			if(session.getAttribute(Constant.OPERATIONMSG)!=null)
			{
				String[] msg=(String[]) session.getAttribute(Constant.OPERATIONMSG);
				log.setOperatorTable(msg[0]);
				log.setOperatorTableId(msg[1]);
				log.setOperatorType(msg[2]);
				log.setOperatorContent(msg[3]);
				log.setOperatorModules(msg[4]);
				//需要立即丢弃session中的存值
				session.removeAttribute(Constant.OPERATIONMSG);
				commonService.insert(log);
			}
		}
		return result;
	}
}
